#pragma once
#include <iostream>
#include <string>
#include <fstream>
#include <set>

using namespace std;

class Command
{
    void Load()
    {
        fstream in(_filename);
        if(!in.is_open())
        {
            cout << "open fail" << endl;
            exit(0);
        }

        string line;
        while(getline(in, line))
        {
            _com.insert(line);
        }
        in.close();
    }
    bool IsExist(const string& str)
    {
        auto pos = _com.find(str);
        if(pos == _com.end())
        {
            return false;
        }
        return true;
    }
public:
    Command(const string &name):_filename(name)
    {
        Load();
    }

    string Excute(const string &str)
    {
        string ret;
        if(IsExist(str))
        {
            FILE *fp = popen(str.c_str(), "r");
            if(fp == nullptr)
            {
                return "popen error";
            }

            char buffer[1024];
            while(fgets(buffer, sizeof(buffer)-1, fp) != nullptr)
            {
                ret += buffer;
            }
            pclose(fp);
        }
        else 
        {
            return "不安全指令";
        }
        return ret;
    }

    ~Command()
    {
        
    }

private:
    set<string> _com;
    string _filename;
};